package com.example.dj;

import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {  
    private ListView mMusiclist; // 音乐列表  
    private List<Mp3Info> mp3Infos = null;  
    private SimpleAdapter mAdapter; // 适配
    private ImageView previousBtn; // 上一首
    private ImageView repeatBtn; // 重复 
    private ImageView playBtn; // 播放/播放/暂停
    private ImageView shuffleBtn; // 随机播放  
    private ImageView nextBtn; // 下一首
    private TextView musicTitle;//歌曲标题  
    private TextView musicDuration; //歌曲时间  
  
    private int repeatState;        //循环标识  
    private final int isAllRepeat = 1; // 全部循环  
    private final int isNoneRepeat = 2; // 无重复播
    private boolean isFirstTime = true;   
    private boolean isPlaying; // 正在播放  
    private boolean isPause; // 暂停  
    private boolean isNoneShuffle = true; // 顺序播放  
    private boolean isShuffle = false; // 随机播放  
      
      
    private int listPosition = 0;   //标识列表位置  
    private BroadcastReceiver homeReceiver;  //自定义的广播接收
    //�?��列动�? 
    public static final String UPDATE_ACTION = "com.example.action.UPDATE_ACTION";  // 更新动作
    public static final String CTL_ACTION = "com.example.action.CTL_ACTION";  // 控制动作
    public static final String MUSIC_CURRENT = "com.example.action.MUSIC_CURRENT";  // 当前音乐改变动作
    public static final String MUSIC_DURATION = "com.example.action.MUSIC_DURATION";  // 音乐时长改变动作
    public static final String REPEAT_ACTION = "com.example.action.REPEAT_ACTION";  // 音乐重复改变动作
    public static final String SHUFFLE_ACTION = "com.example.action.SHUFFLE_ACTION";  // 音乐随机播放动作
      
      
    private int currentTime;  
    private int duration;  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
  
        mMusiclist = (ListView) findViewById(R.id.music_list);  
        mMusiclist.setOnItemClickListener((OnItemClickListener) new MusicListItemClickListener());  
        mMusiclist.setOnCreateContextMenuListener((OnCreateContextMenuListener) new MusicListItemContextMenuListener());  
        mp3Infos = MediaUtil.getMp3Infos(getApplicationContext());  //获取歌曲对象集合  
        //setListAdpter(MediaUtil.getMusicMaps(mp3Infos));    //显示歌曲列表  
        findViewById();             //找到界面上的每一个控键
        setViewOnclickListener();   //为一些控件设置监听器  
        repeatState = isNoneRepeat; // 初始状为无重复播放  
          
          
        homeReceiver = new HomeReceiver();  
        // 创建IntentFilter  
        IntentFilter filter = new IntentFilter();  
        // 指定BroadcastReceiver监听的Action  
        filter.addAction(UPDATE_ACTION);  
        filter.addAction(MUSIC_CURRENT);  
        filter.addAction(MUSIC_DURATION);  
        filter.addAction(REPEAT_ACTION);  
        filter.addAction(SHUFFLE_ACTION);  
        // 注册BroadcastReceiver  
        registerReceiver(homeReceiver, filter);  
          
  
    }  

	/** 
     * 从界面上根据id获取按钮 
     */  
    private void findViewById() {  
        repeatBtn = (ImageView) findViewById(R.id.repeat);  
        shuffleBtn = (ImageView) findViewById(R.id.shuffle);  
        previousBtn = (ImageView) findViewById(R.id.previous);  
        playBtn = (ImageView) findViewById(R.id.play);  
        nextBtn = (ImageView) findViewById(R.id.next);  
        musicTitle = (TextView) findViewById(R.id.title);  
        musicDuration = (TextView) findViewById(R.id.duration);  
    }  
  
    /** 
     * 给按钮设置监听
     */  
    private void setViewOnclickListener() {  
        ViewOnClickListener viewOnClickListener = new ViewOnClickListener();  
        previousBtn.setOnClickListener((OnClickListener) viewOnClickListener);  
        repeatBtn.setOnClickListener(viewOnClickListener);  
        playBtn.setOnClickListener(viewOnClickListener);  
        shuffleBtn.setOnClickListener(viewOnClickListener);  
        nextBtn.setOnClickListener(viewOnClickListener);  
    }  
  
    private class ViewOnClickListener implements OnClickListener {
    	Intent intent = new Intent();
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {  
            case R.id.previous: // 上一首
                isFirstTime = false;  
                isPlaying = true;  
                isPause = false;  
                previous_music();  
                break;  
            case R.id.repeat: // 重复播放  
                if (repeatState == isAllRepeat) {  
                    repeat_none();  
                    shuffleBtn.setClickable(true);  
                    repeatState = isNoneRepeat;  
                }  
                switch (repeatState) {
				case isAllRepeat: // 全部循环
					Toast.makeText(MainActivity.this, null,
							Toast.LENGTH_SHORT).show();
					break;
				case isNoneRepeat: // 无重复
					Toast.makeText(MainActivity.this, null,
							Toast.LENGTH_SHORT).show();
					break;
				}
                break;  
            case R.id.play: // 播放音乐  
                if(isFirstTime) {  
                    play();  
                    isFirstTime = false;  
                    isPlaying = true;  
                    isPause = false;  
                } else {  
                    if (isPlaying) {  
                        intent.setAction("com.example.media.MUSIC_SERVICE");  
                        intent.putExtra("MSG", AppConstant.PlayerMsg.PAUSE_MSG);  
                        startService(intent);  
                        isPlaying = false;  
                        isPause = true;  
                          
                    } else if (isPause) {  
                        intent.setAction("com.example.media.MUSIC_SERVICE");  
                        intent.putExtra("MSG", AppConstant.PlayerMsg.CONTINUE_MSG);  
                        startService(intent);  
                        isPause = false;  
                        isPlaying = true;  
                    }  
                }  
                break;  
            case R.id.shuffle: // 随机播放  
                if (isNoneShuffle) {  
                    Toast.makeText(MainActivity.this, 
                            null, Toast.LENGTH_SHORT).show();  
                    isNoneShuffle = false;  
                    isShuffle = true;  
                    shuffleMusic();  
                    repeatBtn.setClickable(false);  
                } else if (isShuffle) {  
                    Toast.makeText(MainActivity.this, null,  
                            Toast.LENGTH_SHORT).show();  
                    isShuffle = false;  
                    isNoneShuffle = true;  
                    repeatBtn.setClickable(true);  
                }  
                break;  
            case R.id.next: // 下一�? 
                isFirstTime = false;  
                isPlaying = true;  
                isPause = false;  
                next_music();  
                break;  
            }  
		}
		}  
  
    private class MusicListItemClickListener implements OnItemClickListener {  
        /** 
         * 点击列表播放音乐 
         */  
        @Override  
        public void onItemClick(AdapterView<?> parent, View view, int position,  
                long id) {  
            listPosition = position;  
            playMusic(listPosition);          
        }  
  
    }  
      
    public class MusicListItemContextMenuListener implements OnCreateContextMenuListener {  
  
		@Override
		public void onCreateContextMenu(ContextMenu menu, View v,
				ContextMenuInfo menuInfo) {
			// TODO Auto-generated method stub
			 Vibrator vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);  
	            vibrator.vibrate(50);       //长按振动  
		}  
  
    }  
  
    /** 
     * 填充列表 
     *  
     * @param mp3Infos 
     */  
    public void setListAdpter(List<HashMap<String, String>> mp3list) {  
        mAdapter = new SimpleAdapter(this, mp3list,  
                R.layout.list, new String[] { "title",  
                        "Artist", "duration" }, new int[] { R.id.title,  
                        R.id.artist, R.id.duration });  
        mMusiclist.setAdapter(mAdapter);  
    }  
      
      
    /** 
     * 下一首歌
     */  
    public void next_music() {  
        listPosition = listPosition + 1;  
        if(listPosition <= mp3Infos.size() - 1) {  
            Mp3Info mp3Info = mp3Infos.get(listPosition);  
            musicTitle.setText(mp3Info.getTitle());  
            Intent intent = new Intent();  
            intent.setAction("com.example..media.MUSIC_SERVICE");  
            intent.putExtra("listPosition", listPosition);  
            intent.putExtra("url", mp3Info.getUrl());  
            intent.putExtra("MSG", AppConstant.PlayerMsg.NEXT_MSG);  
            startService(intent);  
        } else {  
            Toast.makeText(MainActivity.this, "没有下一首了", Toast.LENGTH_SHORT).show();  
        }  
    }  
  
    /** 
     * 上一首歌
     */  
    public void previous_music() {  
        listPosition = listPosition - 1;  
        if(listPosition >= 0) {  
            Mp3Info mp3Info = mp3Infos.get(listPosition);  
            musicTitle.setText(mp3Info.getTitle());  
            Intent intent = new Intent();  
            intent.setAction("com.example..media.MUSIC_SERVICE");  
            intent.putExtra("listPosition", listPosition);  
            intent.putExtra("url", mp3Info.getUrl());  
            intent.putExtra("MSG", AppConstant.PlayerMsg.PRIVIOUS_MSG);  
            startService(intent);  
        }else {  
            Toast.makeText(MainActivity.this, "没有上一首了", Toast.LENGTH_SHORT).show();  
        }  
    }  
  
    public void play() {  
        Mp3Info mp3Info = mp3Infos.get(listPosition);  
        musicTitle.setText(mp3Info.getTitle());  
        Intent intent = new Intent();  
        intent.setAction("com.example..media.MUSIC_SERVICE");  
        intent.putExtra("listPosition", 0);  
        intent.putExtra("url", mp3Info.getUrl());  
        intent.putExtra("MSG", AppConstant.PlayerMsg.PLAY_MSG);  
        startService(intent);  
    }  
      
    /** 
     * 全部循环 
     */  
    public void repeat_all() {  
        Intent intent = new Intent(CTL_ACTION);  
        intent.putExtra("control", 1);  
        sendBroadcast(intent);  
    }  
  
    /** 
     * 顺序播放 
     */  
    public void repeat_none() {  
        Intent intent = new Intent(CTL_ACTION);  
        intent.putExtra("control", 2);  
        sendBroadcast(intent);  
    }  
      
    /** 
     * 随机播放 
     */  
    public void shuffleMusic() {  
        Intent intent = new Intent(CTL_ACTION);  
        intent.putExtra("control", 3);  
        sendBroadcast(intent);  
    }  
  
    public void playMusic(int listPosition) {  
        if (mp3Infos != null) {  
            Mp3Info mp3Info = mp3Infos.get(listPosition);  
            musicTitle.setText(mp3Info.getTitle());  
            Intent intent = new Intent(MainActivity.this, PlayActivity.class);  
            intent.putExtra("title", mp3Info.getTitle());     
            intent.putExtra("url", mp3Info.getUrl());  
            intent.putExtra("artist", mp3Info.getArtist());  
            intent.putExtra("listPosition", listPosition);  
            intent.putExtra("currentTime", currentTime);  
            intent.putExtra("repeatState", repeatState);  
            intent.putExtra("shuffleState", isShuffle);  
            intent.putExtra("MSG", AppConstant.PlayerMsg.PLAY_MSG);  
            startActivity(intent);  
        }  
    }  
      
    @Override  
    protected void onStop() {  
        // TODO Auto-generated method stub  
        super.onStop();  
    }  
      
      
    @Override  
    protected void onDestroy() {  
        // TODO Auto-generated method stub  
        super.onDestroy();  
    }  
      
    //自定义的BroadcastReceiver，负责监听从Service传回来的广播  
    public class HomeReceiver extends BroadcastReceiver {  
  
        @Override  
        public void onReceive(Context context, Intent intent) {  
            String action = intent.getAction();   
            if(action.equals(MUSIC_CURRENT)){  
                //currentTime代表当前播放的时�? 
                currentTime = intent.getIntExtra("currentTime", -1);  
                musicDuration.setText(MediaUtil.formatTime(currentTime));  
            } else if (action.equals(MUSIC_DURATION)) {  
                duration = intent.getIntExtra("duration", -1);  
            }  
            else if(action.equals(UPDATE_ACTION)) {  
                //获取Intent中的current消息，current代表当前正在播放的歌�? 
                listPosition = intent.getIntExtra("current", -1);  
                if(listPosition >= 0) {  
                    musicTitle.setText(mp3Infos.get(listPosition).getTitle());  
                }  
            }else if(action.equals(REPEAT_ACTION)) {  
                repeatState = intent.getIntExtra("repeatState", -1);  
                switch (repeatState) {  
                case isAllRepeat: // 全部循环  
                    shuffleBtn.setClickable(false);  
                    break;  
                case isNoneRepeat: // 无重复
                    shuffleBtn.setClickable(true);  
                    break;  
                }  
            }  
            else if(action.equals(SHUFFLE_ACTION)) {  
                isShuffle = intent.getBooleanExtra("shuffleState", false);  
                if(isShuffle) {  
                    isNoneShuffle = false;  
                    repeatBtn.setClickable(false);  
                } else {  
                    isNoneShuffle = true;  
                    repeatBtn.setClickable(true);  
                }  
            }  
        }  
          
    }  
}  